import { useUserStore } from "@/store/modules/user";
import { useLocaleStore } from "@/store/modules/locales";
import { useTagsStore } from "@/store/modules/tags";

import router from "@/router";

import axios from "axios";
import { ElMessage } from "element-plus";
import { wrapperEnv, encrypt, generateRandomString } from "./utils";

// 创建axios对象
const requestHttp = axios.create({
  baseURL: wrapperEnv(),
  // baseURL: `api`,
  timeout: 30000,
});
// token的消息头
const TOKEN_HEADER = "Authorization";
// const useUser = useUserStore();
// ================================= 请求拦截器 =================================
requestHttp.interceptors.request.use(
  (config) => {
    let requestData = {};
    const useLocale = useLocaleStore();
    let nonce = "";
    let data = config.method === "get" ? config.params : config.data;

    config.headers["ACCEPT-LANGUAGE"] =
      useLocale.currentLocale.value == "zh" ? "zh-hans" : "en";

    // 在发送请求之前消息头加入token token
    const useUser = useUserStore();
    const token = useUser.currentUserInfo.token;
    const expire = useUser.currentUserInfo.expire;

    const timestampInSeconds = Math.floor(Date.now() / 1000); // 时间戳
    if (data) {
      data.ts = timestampInSeconds;
    } else {
      data = { ts: timestampInSeconds };
    }
    if (token) {
      config.headers[TOKEN_HEADER] = token;
      let prefix = expire.slice(-3);
      let resultChars = parseInt(prefix, 10);
      // 截取从索引 resultChars 到索引 从它开始32 的字符
      let part1 = token.substring(resultChars, resultChars + 32);
      // 将这个key值作为加密的私钥
      let encrypt_data = encrypt(JSON.stringify(data), part1, "", prefix);
      requestData = { data: encrypt_data };

      // config.headers["ACCEPT_LANGUAGE"] = "en";
    } else {
      nonce = generateRandomString();
      let encrypt_data = encrypt(JSON.stringify(data), "", nonce);
      requestData = { data: encrypt_data };
      delete config.headers[TOKEN_HEADER];
    }
    if (config.method === "get") {
      config.params = {
        ...requestData,
      };
    } else {
      if (!token) {
        config.data = {
          ...requestData,
        };
      } else {
        config.data = requestData;
      }
    }
    return config;
  },
  (error) => {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

// ================================= 响应拦截器 =================================

// 添加响应拦截器
requestHttp.interceptors.response.use(
  (response) => {
    // 对响应数据做点什么
    const res = response.data;
    const url = response.config.url;
    const useUser = useUserStore();
    const useTags = useTagsStore();

    if (res.code && res.code != 0) {
      if (res.code === 10001) {
        useUser.clearUserInfo();
        useUser.clearPermissions();
        // 关闭标签
        useTags.closeMultipleTab();

        ElMessage({
          showClose: true,
          message: "登录过期，请重新登录！",
          type: "error",
          grouping: true,
        });

        router.replace({ name: "login", query: {} });
      } else {
        if (url === "/api/mer/wallet/validaddress") {
          // 对于特定接口，不显示后端的错误提示
        } else {
          ElMessage({
            showClose: true,
            message: res.message,
            type: "error",
            grouping: true,
          });
        }
      }
      return Promise.reject(response);
    } else {
      // ElMessage({
      //     showClose: true,
      //     message: res.message,
      //     type: 'success'
      // })
      if (res.data) {
        // 返回接口的data数据
        return Promise.resolve(res.data);
      } else {
        // 直接返回res，防止文件导出等报错
        return Promise.resolve(res);
      }
    }
  },
  (error) => {
    console.log("报错信息", error);

    if (error.message.indexOf("timeout") != -1) {
      ElMessage({
        showClose: true,
        message: "网络超时",
        type: "error",
        grouping: true,
      });
    } else if (error.message == "Network Error") {
      ElMessage({
        showClose: true,
        message: "网络连接错误",
        type: "error",
        grouping: true,
      });
    } else if (error.message.indexOf("Request") != -1) {
      ElMessage({
        showClose: true,
        message: "网络发生错误",
        type: "error",
        grouping: true,
      });
    }

    return Promise.reject(error);
  }
);

// ================================= 对外提供请求方法：通用请求，get， post, 下载download等 =================================

/**
 * 通用请求封装
 * @param config
 */
export const request = (config) => {
  return requestHttp.request(config);
};

/**
 * post请求
 */
export const postRequest1 = (url, data, responseType) => {
  const type = responseType || "json";
  return request({ data, url, method: "post", responseType: type });
};

/**
 * get请求
 */
export const getRequest1 = (url, params, responseType) => {
  const type = responseType || "json";
  return request({ url, method: "get", params, responseType: type });
};
/**
 * delete请求
 */
export const deleteRequest1 = (url, params) => {
  return request({ url, method: "delete", params });
};
